package com.lh.java.jsp.postandget;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class TestJspPost {
	HttpURLConnection conn = null;
	BufferedWriter bWriter = null;
	OutputStream os = null;
	OutputStreamWriter osw = null;
	FileReader fr = null;
	BufferedReader br = null;
	String str = "";
	char c = '\n';
	String filename = "d:/shchinamobile.log";
	public static void main(String[] args) {
		TestJspPost pu = new TestJspPost();
	        try {
	            pu.sendPost("http://127.0.0.1:8080/testjava/testp.jsp");
	        } catch (Exception e) {
	            e.printStackTrace();
	        }

	}

    /**
     * 通过HTTP协议以POST形式发送指定文件至指定url
     * @param url
     * @throws IOException
     */
    public void sendPost(String url) {
        
        try {
            File f = new File(filename);
            
            URL url1 = new URL(url);
            conn = (HttpURLConnection)url1.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setUseCaches( false);
            conn.setDoOutput(true);
            osw = new OutputStreamWriter(conn.getOutputStream());
            fr = new FileReader(f);
            br = new BufferedReader(fr);
            while((str = br.readLine()) != null) {
                osw.write(str);
                osw.write(c);
            }
            osw.flush() ;
            osw.close() ;
            
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK)
                System.out.println( "connect failed!");
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
        finally
        {
            if (osw != null)
                try {
                    osw.close() ;
                } catch (IOException e1) {
                    e1.printStackTrace(System.out);
                }
            
            if (conn != null)
                conn.disconnect() ;
        }
    }    
}
